import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'

import store from '@/store'

const Login = () => import('@/views/login')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list')
const Prodetail = () => import('@/views/prodetail')
const Pay = () => import('@/views/pay')
const Myorder = () => import('@/views/myorder')
const AddressList = () => import('@/views/addressList')
const AddressAdd = () => import('@/views/addressAdd')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/cart', component: Cart },
        { path: '/category', component: Category },
        { path: '/user', component: User }
      ]
    },
    { path: '/myorder', component: Myorder },
    { path: '/pay', component: Pay },
    { path: '/prodetail', component: Prodetail },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    { path: '/addresslist', component: AddressList },
    { path: '/addressadd', component: AddressAdd }
  ]
})

// 全局前置导航守卫
// to:   即将要进入的目标
// from: 当前导航正要离开的路由
const authUrls = ['/pay', '/myorder', '/address']
router.beforeEach((to, from, next) => {
  // 看to.path 是否在 authUrls 中出现
  if (!authUrls.includes(to.path)) {
    // 非权限页面，直接放行
    next()
    return
  }

  // 是权限页面，需要判断token
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
